package api;

import cn.hutool.db.Db;
import cn.hutool.json.JSONUtil;
import common.ApplicationVariable;
import lombok.SneakyThrows;
import model.ResultData;
import model.UserInfo;
import util.DBUtil;
import util.SessionUtil;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 *  删除点菜
 */
@WebServlet("/deldish")
public class DelDishServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int state=-1;
        String msg="未知错误";
        // 验证登录信息
        UserInfo userInfo= SessionUtil.getSessionUserInfo(req);
        if(userInfo!=null){ //已经登录
            Integer did=Integer.parseInt(req.getParameter("did"));
            if(did!=null&&did>0){
                // 参数有意义，执行删除操作
                Connection connection= DBUtil.getConnection();
                String sql="delete from dish where did=?";
                PreparedStatement statement=connection.prepareStatement(sql);
                statement.setInt(1,did);
                int result=statement.executeUpdate();
                DBUtil.close(null,statement,connection);
                state=result>=1?200:-1;
            }else{
                msg="参数错误";
            }
        }
        // 将结果返回给前端
        resp.setContentType(ApplicationVariable.RESPONSE_CONTENT_TYPE);
        resp.getWriter().println(JSONUtil.toJsonStr(new ResultData(state,"",msg)));
    }
}
